/*
 * @(#)LoginRequiredInterceptor.java 1.0 2019年1月8日上午11:17:23
 *
 * 
 * Copyright (c) , Inc. All rights reserved.
 */
package com.saturn.config.server.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * <dl>
 *    <dt><b>Title:</b></dt>
 *    <dd>
 *    	none
 *    </dd>
 *    <dt><b>Description:</b></dt>
 *    <dd>
 *    	<p>none
 *    </dd>
 * </dl>
 *
 * @author tanks
 * @version 1.0, 2019年1月8日
 * @since JdbcConfigServer
 * 
 */
@Component
public class LoginRequiredInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Object user = request.getSession().getAttribute("useInfo");
        if (user == null) {
        	if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				String encode = request.getCharacterEncoding();
				response.resetBuffer();
				response.setHeader("passwdexpried", "true");
				String jsonText = "{\"success\":false,\"msg\":\"登录尝试，请重新登录\",\"loginUrl\":\"#\",\"allowAccess\":false}";
				response.setCharacterEncoding(encode);
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write(jsonText);
				return false;
			}else {
				response.sendRedirect("/static/login.html");
			}
        }
        return super.preHandle(request, response, handler);
	}
}
